package com.chain.BrotherExchange.im;

import android.os.Handler;
import android.os.Looper;

import com.chain.BrotherExchange.im.entity.AuthenticationMessage;
import com.chain.BrotherExchange.im.entity.ReceiveMessage;
import com.chain.BrotherExchange.im.entity.SendMessage;
import com.google.gson.Gson;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.WebSocket;

import static com.chain.BrotherExchange.im.entity.ReceiveMessage.AUTHENTICATION_TYPE;
import static com.chain.BrotherExchange.im.entity.ReceiveMessage.MESSAGE_TYPE;

/**
 * 即时通信 web socket
 */
public class IMWebSocket {

    private int uid;
    private int buyerId;
    private int sellerId;
    private String token;
    private String orderId;
    private String username;

    private WebSocket mWebSocket;
    private Handler mMainThreadHandler;
    private ReceiveCallback mReceiveCallback;
    private ConnectionListener mConnectionListener;
    private AuthenticationListener mAuthenticationListener;

    /**
     * 连接监听
     */
    public interface ConnectionListener {
        void connection(boolean status);
    }

    /**
     * 认证监听
     */
    public interface AuthenticationListener {
        void onAvailable();
    }

    /**
     * 接收消息回调
     */
    public interface ReceiveCallback {
        void onAvailable(ReceiveMessage message);
    }

    public IMWebSocket(String uri, String port) {
        mMainThreadHandler = new Handler(Looper.myLooper());

        AsyncHttpClient.getDefaultInstance().websocket(uri, port, (ex, webSocket) -> {
            if (ex == null) {
                this.mWebSocket = webSocket;

                if (mConnectionListener != null) {
                    mConnectionListener.connection(true);
                }

                mWebSocket.setStringCallback(messageJson -> {
                    ReceiveMessage message = new Gson().fromJson(messageJson, ReceiveMessage.class);
                    if (message != null) {
                        if (message.getResp_type() == AUTHENTICATION_TYPE && mAuthenticationListener != null) {
                            mMainThreadHandler.post(() -> mAuthenticationListener.onAvailable());
                        } else if (message.getResp_type() == MESSAGE_TYPE && mReceiveCallback != null) {
                            mMainThreadHandler.post(() -> this.mReceiveCallback.onAvailable(message));
                        }
                    }
                });
            } else {
                mConnectionListener.connection(false);
            }
        });
    }

    // 认证
    public void authentication(
            String token, int uid, String username, String orderId, int sellerId, int buyerId,
            AuthenticationListener authenticationListener) {
        this.token = token;
        this.uid = uid;
        this.username = username;
        this.orderId = orderId;
        this.sellerId = sellerId;
        this.buyerId = buyerId;
        this.mAuthenticationListener = authenticationListener;

        mWebSocket.send(new Gson().toJson(new AuthenticationMessage(token, orderId, sellerId,
                uid, buyerId, username)));
    }

    // 发送认证消息
    public void connection(ConnectionListener connectionListener) {
        if (mWebSocket == null) {
            this.mConnectionListener = connectionListener;
        } else {
            connectionListener.connection(true);
        }
    }

    // 发送文字
    public void sendText(String message) {
        if (mWebSocket != null) {
            mWebSocket.send(new Gson().toJson(new SendMessage(token, message, orderId, username,
                    sellerId, buyerId, uid)));
        }
    }

    public void setReceiveCallback(ReceiveCallback callback) {
        this.mReceiveCallback = callback;
    }
}
